<template>
  <el-dialog title="角色" v-model="visible" :close-on-click-modal="false" :show-close="false" :close-on-press-escape="false" width="400px">
    <el-form ref="formRef" :model="authData.form" label-width="80px" label-position="left" :status-icon="true" :show-message="false">
      <el-form-item label="角色名称" prop="authorityName" required>
        <el-input class="third_input" v-model="authData.form.authorityName" placeholder="请输入角色名称" clearable></el-input>
      </el-form-item>
    </el-form>
    <div class="tree">
      <el-tree ref="treeRef" v-model="authData.form.pageIds" :data="authData.pageData" show-checkbox node-key="supplierPageId" :props="authData.defaultProps" default-expand-all> </el-tree>
    </div>
    <template #footer>
        <Button label="取消" @click="onCancelClick" />
        <Button label="确认" type="primary" @click="onSubmitClick" />
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, reactive, ref, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/api'
import Button from '@/components/button/button.vue'

const emit = defineEmits(['update:visible', 'change'])
const props = defineProps(['visible', 'list', 'form'])

const visible = computed({
  get: () => {
    return props.visible
  },
  set: (value) => emit('update:visible', value)
})

watch(
  () => props.form,
  (val) => {
    authData.form = val
    if (authData.form.supplierAuthorityId) {
      pageData(authData.form.supplierAuthorityId)
    }
  }
)

const formRef = ref()
const treeRef = ref()

const authData = reactive({
  form: {},
  defaultProps: {
    children: 'pages',
    label: 'pageName'
  },
  pageData: []
})

const pageData = async (authorityId) => {
  let { data, err } = await api.get(`/medinstrument/third/authority/${authorityId}`)
  if (err) {
    ElMessage.error(err)
  } else {
    let pageIds = data.authorityPageMapList.map((item) => item.supplierPageId)
    nextTick(() => {
      treeRef.value.setCheckedKeys(pageIds)
    })
  }
}

const authPageData = async () => {
  let { data, err } = await api.get('/medinstrument/third/page/getAllPages')
  if (err) {
    ElMessage.error(err)
  } else {
    authData.pageData = data.authPageList
  }
}

const hide = () => {
  visible.value = false
  nextTick(() => {
    formRef.value.clearValidate()
    treeRef.value.setCheckedKeys([])
  })
}

const onCancelClick = () => {
  hide()
}
const onSubmitClick = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      authData.form.pageIds = treeRef.value.getCheckedKeys().join(',')
      emit('change', authData.form)
      hide()
    }
  })
}

onMounted(() => {
  authPageData()
})
</script>

<style scoped>
.tree {
  height: 300px;
  overflow-y: auto;
}
</style>
